#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Conexión 3G
# Copyright (C) 2009 Plan Ceibal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact information: comunidad@plan.ceibal.edu.uy
# Plan Ceibal http://www.ceibal.edu.uy

import os, sys, subprocess, fcntl, time, select
import shutil, string
import getopt
import InterfazGlade
import logging
# Permite generar y leer el archivo de configuración que lee el cliente wvdial
# Permite generar el archivo resolv.conf mediante el wrapper wvdial-wrapper

Path_WVdial_Config = '/home/local/.wvdial.conf'

class Conexion3GConfiguracion:
	def __init__(self):
		self.Modem = ''
		self.ModemType = ''
		self.Baud = ''
		self.Init  = ''
		self.Init2 = ''
		self.Phone  = ''
		self.AskPassword = False
		self.Password = ''
		self.Username = ''
		self.Dns1 = ''
		self.Dns2 = ''
		self.InitString1 = ''
		self.InitString2 = ''
		self.InitString3 = ''
		self.AutoDns = True
		self.stupid_mode = True
		self.Pin = ''
		self.Puk = ''
		self.requierePuk = False
	
# Metodos Globales 
def getModem3GConfiguracion():
	# Leer archivo de Configuracion 
	config3G = Conexion3GConfiguracion()
	try:
		if os.path.exists(Path_WVdial_Config):
			lines = open(Path_WVdial_Config, 'r') 
			for line in lines:	
				if line.startswith('Modem ='):
					config3G.Modem = lineSplitSignoIgual(line, 'Modem = ')
					continue
				if line.startswith('Modem Type ='):
					config3G.ModemType = lineSplitSignoIgual(line, 'Modem Type =') 
					continue
				if line.startswith('Baud ='):
					config3G.Baud =  lineSplitSignoIgual(line, 'Baud =') 
					continue
				if line.startswith('Init ='):
					config3G.InitString1 = lineSplitSignoIgual(line, 'Init =') 
					continue
				if line.startswith('Init2 ='):
					config3G.InitString2 = lineSplitSignoIgual(line, 'Init2 =') 
					continue
				if line.startswith('Init3 ='):
					config3G.InitString3 = lineSplitSignoIgual(line, 'Init3 =') 
					continue
				if line.startswith('Phone ='):
					config3G.Phone = lineSplitSignoIgual(line, 'Phone =') 
					continue
				if line.startswith('Ask Password ='):
					config3G.AskPassword = getBoolBySplitLine(line, 'Ask Password =')  
					continue
				if line.startswith('Stupid Mode ='):
					config3G.stupid_mode = getBoolBySplitLine(line, 'Stupid Mode =')  
					continue
				if line.startswith('Auto DNS ='):
					config3G.AutoDns = getBoolBySplitLine(line, 'Auto DNS =')  
					continue
				if line.startswith('Password ='):
					config3G.Password = lineSplitSignoIgual(line, 'Password =')   
					continue
				if line.startswith('Username ='):
					config3G.Username = lineSplitSignoIgual(line, 'Username =')    
					continue
				if line.startswith(';Nameserver ='):
					config3G.Dns1 = lineSplitSignoIgual(line, ';Nameserver =')       
					continue
				if line.startswith(';Nameserver2 ='):
					config3G.Dns2 = lineSplitSignoIgual(line, ';Nameserver2 =')  
					continue
				if line.startswith(';Pin ='):
					config3G.Pin = lineSplitSignoIgual(line, ';Pin =')  
					continue
				if line.startswith(';Puk ='):
					config3G.Puk = lineSplitSignoIgual(line, ';Puk =')  
					continue
		else:
			raise InterfazGlade.ExcepcionErrorInstalacion("Faltan dependencias, no está instalado wvdial-wrapper. Falta archivo de configuración /home/local/.wvdial.wrapper")
	except Exception, e:	
		_logger = logging.getLogger('Conexion3G-activity')
		_logger.setLevel(logging.DEBUG)
		_logger.debug("Error leyendo el archivo de configuración")
		raise e
	return config3G

def setModem3gConfiguracion(config3G):
	# Escribir archivo de Configuracion
	outfile = open(Path_WVdial_Config, 'w') 
	outfile.write("[Dialer Pin]\n")
	if (config3G.Puk <> '' and config3G.requierePuk):
		outfile.write("Init1 = AT+CPIN="+ config3G.Puk + ", "+ config3G.Pin + "\n")
	else: outfile.write("Init1 = AT+CPIN= "+ config3G.Pin + "\n")
	outfile.write("Modem = "+ config3G.Modem +"\n")

	outfile.write("[Dialer Connection]\n")
	outfile.write("Modem = "+ config3G.Modem +"\n")
	outfile.write("ISDN = off\n")
	outfile.write("Modem Type = " + config3G.ModemType + "\n")
	outfile.write("Baud = "+ config3G.Baud + "\n")

	outfile.write("Init1 = " + config3G.InitString1 + "\n")
	outfile.write("Init2 = "+ config3G.InitString2 + "\n")
	outfile.write("Init3 = "+ config3G.InitString3 + "\n")
	outfile.write("Init4 = \n")
	outfile.write("Init5 = \n")
	outfile.write("Init6 = \n")
	outfile.write("Init7 = \n")
	outfile.write("Init8 = \n")
	outfile.write("Init9 = \n")
	outfile.write("Phone = "+ config3G.Phone +"\n")
	outfile.write("Phone1 = \n")
	outfile.write("Phone2 = \n")
	outfile.write("Phone3 = \n")
	outfile.write("Phone4 = \n")
	outfile.write("Dial Prefix = \n")
	outfile.write("Dial Attempts = 1\n")
	outfile.write("Dial Command = ATM1L3DT\n")

	if (config3G.AskPassword):
		outfile.write("Ask Password = on\n")
	else:
		outfile.write("Ask Password = off\n")

	outfile.write("Password = "+ config3G.Password + "\n")

	outfile.write("Username = " + config3G.Username + "\n")
	outfile.write("Auto Reconnect = off\n")
	outfile.write("Abort on Busy = off\n")
	outfile.write("Carrier Check = on\n")
	outfile.write("Check Def Route = on\n")
	outfile.write("Abort on No Dialtone = on\n")

	if (config3G.stupid_mode):
		outfile.write("Stupid Mode = on\n")
	else:
		outfile.write("Stupid Mode = off\n")

	outfile.write("Idle Seconds = 0\n")

	if (config3G.AutoDns):
		outfile.write("Auto DNS = on\n")
	else:
		outfile.write("Auto DNS = off\n")

	outfile.write(";Domain = \n")
	outfile.write(";Nameserver = "+ config3G.Dns1 + "\n")
	outfile.write(";Nameserver2 = " + config3G.Dns2 + "\n")
	outfile.write(";Minimize = off\n")
	outfile.write(";Dock = off\n")
	outfile.write(";Do NOT edit this file by hand!\n")
	outfile.write(";Pin ="+ config3G.Pin +"\n")
	outfile.write(";Puk ="+ config3G.Puk +"\n")

	outfile.close()

def setModem3gDnsConfiguracion(Dns1, Dns2):
	# Escribir resolv.conf
	command=[ InterfazGlade.PATH_WVDIAL, 'configureDns', Dns1, Dns2]
	ps = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
	if (ps != None and ps != ""):
		raise Exception("Error:" + ps)
	    
########### Auxiliares
def lineSplitSignoIgual(line, tag):
	return line.partition(tag)[2].replace('\'','').replace('\n','').lstrip()

def getBoolBySplitLine(line, tag):
	AuxStr = lineSplitSignoIgual(line, tag)  
	if (AuxStr== "off"):
		return False	
	else:
		return True



